package cn.wen.service.impl;

import cn.wen.dao.UserDao;
import cn.wen.entity.User;
import cn.wen.mapper.UserMapper;
import cn.wen.myservice.UserCacheService;
import cn.wen.service.UserService;
import cn.wen.utils.MD5Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author FY
 * @since 2022-02-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${user.avatar}")
    private String defaultAvatar;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserDao userDao;

    @Resource
    private UserCacheService cacheService;

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getUserByEmail(String email) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("email",email);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean updateUsrById(User user) {
        User dbUser = userMapper.selectById(user.getId());
        if (!dbUser.getPassword().equals(user.getPassword()) && user.getPassword() != null){
            user.setPassword(MD5Util.md5(user.getPassword()+dbUser.getSalt()));
        }
        cacheService.delUser(user.getId());
        cacheService.setUser(user);
        return userDao.updateUser(user) > 0;
    }

    @Override
    public boolean createUser(User user) {
        User resultUser = new User();
        BeanUtils.copyProperties(user,resultUser);
        String salt = MD5Util.saltUtil();
        resultUser.setPassword(MD5Util.md5(user.getPassword()+salt));
        resultUser.setCreateTime(new Date());
        resultUser.setSalt(salt);
        resultUser.setUpdateTime(new Date());
        resultUser.setAvatar(defaultAvatar);
        return userMapper.insert(resultUser) >0;
    }

    @Override
    public User getUserByUsername(String username) {
        // 先从redis中获取
        User user = cacheService.getUser(username);
        if (user!= null)return user;
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        user = userMapper.selectOne(queryWrapper);
        if (user != null){
            cacheService.setUser(user);
            return user;
        }
        return user;
    }
}
